<?php

namespace App\Http\Controllers\Driver;

use App\Enum\CodeEnum;
use App\Events\DriverStart;
use App\Events\OrderOrd;
use App\Http\Controllers\Api\ApiBaseController;

use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;

class UserController extends ApiBaseController
{
    protected $service = null;

    public function __construct(Request $request)
    {
        $this->service = self::getServiceObj();
    }


    /**
     * 生成预警订单
     * @param Request $request
     * @return JsonResponse|null
     */
    public function waringOrder(Request $request): ?JsonResponse
    {
        try {
            $orderId = $request->get('order_id');
            $info = $this->service->addWaringOrder($orderId);
            if ($info !== true) {
                return fail(CodeEnum::ERROR, '生成预警订单失败');
            }
            return success();
        } catch (\Exception $e) {
            return fail(CodeEnum::ERROR, $e->getMessage());
        }
    }

    /**
     * 预警列表
     * @return JsonResponse|null
     */
    public function waringOrderList(): ?JsonResponse
    {
        try {
            $data = $this->service->waringOrderList();
            return success($data);
        } catch (\Exception $e) {
            return fail(CodeEnum::ERROR, $e->getMessage());
        }
    }

    /**
     * 预警订单详情
     * @param Request $request
     * @return JsonResponse|null
     */
    public function waringOrderDetail(Request $request): ?JsonResponse
    {
        try {
            $orderId = $request->get('order_id');
            if(!intval($orderId)){
                throw new \Exception('订单id错误');
            }

            $data = $this->service->waringOrderDetail($orderId);
            return success($data);
        } catch (\Exception $e) {
            return fail(CodeEnum::ERROR, $e->getMessage());
        }
    }

    /**
     * 获取司机信息
     * @return \Illuminate\Http\JsonResponse|void
     * @author ninetyseven.
     * @date 2023-03-28 23:46
     */
    public function getInfo(Request $request)
    {
        try {
            $driverId = $request->get('driver_id');
            $info = $this->service->getDriverInfo($driverId);
            if(!$info){
                throw new \Exception('获取司机信息失败');
            }
            return success($info);
        } catch (\Exception $e) {
            return fail(CodeEnum::ERROR, $e->getMessage());
        }
    }

    /**
     * 上报异常
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|void
     * @author ninetyseven.
     * @date 2023-04-05 11:33
     */
    public function abnormalAdd(Request $request)
    {
        try {
            $post = $request->post();
            $info = $this->service->addAbnormal($post);
            if ($info !== true) {
                throw new \Exception('上报异常失败');
            }

            return success();
        } catch (\Exception $e) {
            return fail(CodeEnum::ERROR, $e->getMessage());
        }
    }

    /**
     * 获取实名信息
     * @return \Illuminate\Http\JsonResponse|void
     * @author ninetyseven.
     * @date 2023-04-02 20:18
     */
    public function getAuthInfo()
    {
        try {
            $info = $this->service->getAuthInfo();
            return success($info);
        } catch (\Exception $e) {
            return fail(CodeEnum::ERROR, $e->getMessage());
        }
    }

    /**
     * 获取车辆信息
     * @return \Illuminate\Http\JsonResponse|void
     * @author ninetyseven.
     * @date 2023-04-02 20:18
     */
    public function getCartInfo()
    {
        try {
            $info = $this->service->getCartInfo();
            return success($info);
        } catch (\Exception $e) {
            return fail(CodeEnum::ERROR, $e->getMessage());
        }
    }

    /**
     * 停止接单
     * @return \Illuminate\Http\JsonResponse|void
     * @author ninetyseven.
     * @date 2023-04-02 22:35
     */
    public function stopOrder()
    {
        try {
            $info = $this->service->modifyDriverStopOrder();
            if ($info === false) {
                return fail(CodeEnum::ERROR, '更新失败');
            }

            return success();
        } catch (\Exception $e) {
            return fail(CodeEnum::ERROR, $e->getMessage());
        }
    }

    /**
     * 开始接单
     * startOrder
     * @return JsonResponse|null
     * @author ninetyseven.
     * @date 2023/4/30
     */
    public function startOrder()
    {
        try {
            $info = $this->service->modifyDriverStartOrder();
            if ($info === false) {
                return fail(CodeEnum::ERROR, '更新失败');
            }

            return success();
        } catch (\Exception $e) {
            return fail(CodeEnum::ERROR, $e->getMessage());
        }
    }

    /**
     * 完成订单后修改距离
     * modifyOrderDistance
     * @param Request $request
     * @return JsonResponse|null
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     * @author ninetyseven.
     * @date 2023/5/8
     */
    public function modifyOrderDistance(Request $request): ?JsonResponse
    {
        try {
            $info = $this->service->modifyOrderDistance($request->post());
            if ($info !== true) {
                return fail(CodeEnum::ERROR, '更新失败');
            }

            return success();
        } catch (\Exception $e) {
            return fail(CodeEnum::ERROR, $e->getMessage());
        }
    }

    /**
     * 订单申诉
     * orderAppeal
     * @param Request $request
     * @author ninetyseven.
     * @date 2023/4/30
     */
    public function orderAppeal(Request $request)
    {
        try {
            $info = $this->service->createOrderAppeal($request->post());
            if ($info === false) {
                return fail(CodeEnum::ERROR, '更新失败');
            }

            return success();
        } catch (\Exception $e) {
            return fail(CodeEnum::ERROR, $e->getMessage());
        }
    }

    /**
     * 抢单
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|void
     * @author ninetyseven.
     * @date 2023-04-05 13:41
     */
    public function orbOrder(Request $request)
    {
        DB::beginTransaction();
        try {
            $post = $request->post();
            if (empty($post['order_id'])) {
                return fail(CodeEnum::PARAM_ERROR, '参数order_id不存在');
            }

            $res = $this->service->orbOrderInfo($post);
            if($res === false){
                throw new \Exception('抢单失败');
            }

            return success($res);
        } catch (\Exception $e) {
            DB::rollBack();
            Log::error($e->getMessage());
            return fail(CodeEnum::ERROR, $e->getMessage());
        }
    }

    /**
     * 获取承包信息
     * @return \Illuminate\Http\JsonResponse|void
     * @author ninetyseven.
     * @date 2023-04-05 16:30
     */
    public function getEnterpriseInfo()
    {
        try {
            throw new \Exception("此方法已经作废");
            $res = $this->service->getEnterpriseInfo();
            return success($res);
        } catch (\Exception $e) {
            Log::error($e->getMessage());
            return fail(CodeEnum::ERROR, $e->getMessage());
        }
    }

    /**
     * 保存里程
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|void
     * @author ninetyseven.
     * @date 2023-04-05 17:21
     */
    public function mileageAdd(Request $request)
    {
        try {
            $post = $request->post();
            $res = $this->service->mileageAdd($post);
            if (!$res) {
                return fail(CodeEnum::ERROR, '保存里程失败');
            }
            return success();
        } catch (\Exception $e) {
            Log::error($e->getMessage());
            return fail(CodeEnum::ERROR, $e->getMessage());
        }
    }

    /**
     * 里程详情
     * @return \Illuminate\Http\JsonResponse|void
     * @author ninetyseven.
     * @date 2023-04-05 18:05
     */
    public function mileageInfo()
    {
        try {
            $res = $this->service->mileageInfo();
            return success($res);
        } catch (\Exception $e) {
            Log::error($e->getMessage());
            return fail(CodeEnum::ERROR, $e->getMessage());
        }
    }

    /**
     * 历史里程
     * @return \Illuminate\Http\JsonResponse|void
     * @author ninetyseven.
     * @date 2023-04-05 18:11
     */
    public function mileageHistoryList()
    {
        try {
            $res = $this->service->getMileageHistoryList();
            return success($res);
        } catch (\Exception $e) {
            return fail(CodeEnum::ERROR, $e->getMessage());
        }
    }

    /**
     * 订单核销
     * @return \Illuminate\Http\JsonResponse|void
     * @author ninetyseven.
     * @date 2023-04-10 11:18
     */
    public function writeOffOrder()
    {
        DB::beginTransaction();
        try {
            $post = request()->post();
            $res = $this->service->writeOffOrder($post);
            return success($res);
        } catch (\Exception $e) {
            DB::rollBack();
            return fail(CodeEnum::ERROR, $e->getMessage());
        }
    }
    public function updateOrderDriverTime(): ?JsonResponse
    {
        DB::beginTransaction();
        try {
            $post = request()->post();
            // 必须要传递司机是来接客还是到达接客地点
            if( isset($post['driver_start_time']) || isset($post['driver_arrived_time']) )
            {
                if(isset($post['driver_arrived_time'])) $post['field'] = 'driver_arrived_time';
                if(isset($post['driver_start_time'])) $post['field'] = 'driver_start_time';

                $adminInfo=[];
                if( isset($post['admin_id']) ) {
                    $adminInfo = [
                        'admin_id' => $post['admin_id'],
                        'admin_name' => $post['admin_name']
                    ];
                }

                $res = $this->service->updateOrderDriverTime($post);
                // 触发司机出发到达的事件20230821 by LC
                event(new DriverStart($res, $adminInfo));

            }else{
                throw new \Exception('司机出发接客时间异常');
            }
            DB::commit();
            return success(true);
        } catch (\Exception $e) {
            Log::error('UserController.updateOrderDriverTime. FAILED=>'. $e->getMessage());
            DB::rollBack();
            return fail(CodeEnum::ERROR, $e->getMessage());
        }
    }
}
